<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Api\BtApiController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use function foo\func;
use Illuminate\Support\Facades\Storage;

class SettingController extends Controller
{
    //RFID编码方案-流水码组成/www/server/panel/plugin/supervisor/profile
    public function RFID_18($gqjID_pro='') {
        //方案名称，地市单位位数，区县单位位数，班站所码位数，电压等级码位数，工具类别码位数，流水码，数量，序号
        $pros = [
            1 => [
                'name'      => '方案一',
                'city'      => '3',
                'area'      => '3',
                'ban'       => '2',
                'vol'       => '2',
                'tool'      => '3',
                'serial'    => '3',
                'sub_count' => '1',
                'sub_num'   => '1',
            ],
            2 => [
                'name'      => '方案二',
                'city'      => '3',
                'area'      => '3',
                'ban'       => '2',
                'vol'       => '2',
                'tool'      => '3',
                'serial'    => '5',
                'sub_count' => '0',
                'sub_num'   => '0',
            ],
        ];
        if($gqjID_pro){
            return $pros[$gqjID_pro] ?:[];
        }
        return $pros;
    }

    //检验标准 修改
    public function edit(Request $request) {
        $id = 1;
        $signs = [  //200,50是高度
            '报告公章|200'=>'report_sign',
            '报告合格章|50'=>'report_sign_hege',
            '报告不合格章|50'=>'report_sign_unhege'
        ]; //样品报告章：公章，合格章，不合格章
        if($request->isMethod('POST')) {
            if(isset($request->set_other)) {
                $setSysData = $request->set_other;
                foreach($setSysData as $key => $val_remark) {
                    $value = array_get($val_remark,'value','');
                    $val_remark['value'] = is_array($value) ? json_encode($value) : $value;
                    if(isset(getCache('setting')[$key])) {
                        DB::table('setting_sys')->where('key', $key)->update($val_remark);
                    }
                    else {
                        $insert = array_merge($val_remark, ['key' => $key]);
                        DB::table('setting_sys')->insert($insert);
                    }
                }
                $this->setCache();
                return 1;
            }
            $post_data = $request->only('name_site','name_rep','name_pass','report_num_pre','chars_count','enable_tool_ID');
            $post_data['enable_tool_ID'] = $request->enable_tool_ID ? 1 : 0;
            //update 返回受影响的行数
            $result = DB::table('setting')->where('id', $id)->update($post_data);
            $this->setCache();
            //上传封面文件（批次报告）
            if($request->hasFile('file_fm') && $request->file_fm->isValid()) {
                $request->file_fm->storeAs("ExcelTemplate", '封面.xls', 'public');
            }
            //上传封面文件（单样品报告）
            if($request->hasFile('solo_file_fm') && $request->solo_file_fm->isValid()) {
                $request->solo_file_fm->storeAs("ExcelTemplate", '单样品封面.xls', 'public');
            }
            //上传封底文件
            if($request->hasFile('file_fd') && $request->file_fd->isValid()) {
                $request->file_fd->storeAs("ExcelTemplate", '封底.xls', 'public');
            }
            //样品报告章
            $uploadcon = new UploadController();
            foreach ($signs as $sign) {
                $report_sign = $request->$sign;
                if($report_sign && substr($report_sign,0,10) == 'data:image') {
                    $res = $uploadcon->render('img', [
                        'dir' => 'ExcelTemplate',
                        'file' => $report_sign,
                        'filename' => "{$sign}.png",
                        'rotate' => 1,
                        'size_max' => 2048, //最大1M
                        'disk' => 'public',
                    ]);
                    if($res['code'] != 1){
                        return $res;
                    }
                }
            }
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result >= 0 ? '1' : '0';
        }
        else {
            $setSys = getCache('setting'); //系统配置信息（setting_sys）
            //查询信息
            $data = DB::table('setting')->find(1);

            //判断批次封面模板文件是否存在
            $template_file = "./storage/ExcelTemplate/封面.xls"; //考虑到兼容Linux，斜杠用“/”
            $exist_template_fm = file_exists($template_file);
            //判断样品封面模板文件是否存在
            $template_file = "./storage/ExcelTemplate/单样品封面.xls"; //考虑到兼容Linux，斜杠用“/”
            $exist_template_solo_fm = file_exists($template_file);
            //判断封底模板文件是否存在
            $template_file = "./storage/ExcelTemplate/封底.xls"; //考虑到兼容Linux，斜杠用“/”
            $exist_template_fd = file_exists($template_file);
            //RFID编码方案-流水码组成
            $gqjID_18_pros = $this->RFID_18();
            return view('admin.setting.edit', compact('setSys', 'data', 'exist_template_fm', 'exist_template_fd','gqjID_18_pros','exist_template_solo_fm','signs'));
        }
    }

    //合格证设置
    public function passedCardSet() {
        $id = 1;
        //setting_sys表中的合格证相关数据的默认值
        $setting_sys = [
                [
                    'key'=>'passedCard_have_barcode', 
                    'value'=>0, 
                    'remark'=>'合格证上是否有二维码，1-有，0-无'
                ], 
                [
                    'key'=>'passedCard_print_ahead', 
                    'value'=>0, 
                    'remark'=>'合格证上是否有二维码，1-有，0-无'
                ], 
                [
                    'key'=>'passedCard_company_name_font_size', 
                    'value'=>39, 
                    'remark'=>'合格证上公司名称文字大小'
                ], 
            ];
        if(request()->isMethod('POST')) {
            $setSys = getCache('setting');
            $columns = array_column($setting_sys,'key');
            $except = array_merge(['_token', 'have_barcode'],$columns);
            $post_data = request()->except($except);
            DB::beginTransaction();
            try{
                //update 返回受影响的行数
                DB::table('setting')->where('id', $id)->update($post_data);
                //更新setting_sys中的数据
                foreach($columns as $column){
                    $value = request($column);
                    if ($setSys[$column] != $value) {
                        DB::table('setting_sys')->where('key', $column)->update(['value'=>$value]);
                    }
                }
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                return $e->getMessage();
            }
            $setSys = $this->setCache();
            //由于框架自身不支持响应bool值，所以转化一种形式
            return '1';
        }
        else {
            //查询信息
            // dd(request()->all());
            $data = DB::table('setting')->find(1);
            $setSys = getCache('setting');
            //更新setting_sys中的数据
            $inCount = 0;
            foreach ($setting_sys as $inData) {
                if(!isset($setSys[$inData['key']])){
                    $inCount += 1;
                    DB::table('setting_sys')->insert($inData);
                }
            }
            $setSys = $inCount > 0 ? $this->setCache() : $setSys;
            return view('admin.setting.passedCardSet', compact('data', 'setSys'));
        }
    }

    //条形码打印设置
    public function printBarCodeSet(Request $request) {
        $key = 'print_bar_code';
        if($request->isMethod('POST')) {
            $post_data = $request->except(['_token']);
            //update 返回受影响的行数
            $exist = DB::table('setting_sys')->where('key', $key)->exists();
            $updata = [];
            $updata['value'] = json_encode($post_data);
            if(!$exist) {
                $insertdata = $updata;
                $insertdata['key'] = $key;
                $insertdata['remark'] = '打印条形码设置';
                $result = DB::table('setting_sys')->insert($insertdata);
            }
            else {
                $result = DB::table('setting_sys')->where('key', $key)->update($updata);
            }
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result >= 0 ? '1' : '0';
        }
        else {
            //查询信息
            $data = DB::table('setting_sys')->where('key', $key)->value('value');
            $data = json_decode($data, true);
            // dd($data);
            if(!isset($data['is_remote_RFID'])) {
                $data['is_remote_RFID'] = "";
            }
            if(!isset($data['remote_ip_RFID'])) {
                $data['remote_ip_RFID'] = "";
            }
            $enable_tool_ID = DB::table('setting')->where('id', '1')->value('enable_tool_ID');
            return view('admin.setting.printBarCodeSet', compact('data', 'enable_tool_ID'));
        }
    }

    //检测地点设置
    public function testPlace() {
        $request = request();
        $key = 'test_place';
        $method = $request->func;
        $val = trim($request->val);
        $result = 0;
        if(strlen($val) > 0) {
            $exist = isset(getCache('setting')[$key]);
            if(!$exist) {
                $insertdata = [];
                $insertdata['value'] = trim($val);
                $insertdata['key'] = $key;
                $insertdata['remark'] = '工器具样品检测地点';
                $result = DB::table('setting_sys')->insert($insertdata);
            }
            else {
                $value = DB::table('setting_sys')->where('key', $key)->value('value');
                if($method === 'add') {
                    $value .= ','.$val;
                    $value = trim($value, ',');
                    $result = DB::table('setting_sys')->where('key', $key)->update(['value' => $value]);
                }
                if($method === 'del') {
                    $value = ','.$value.',';
                    $value = str_replace(','.$val.',', ',', $value);
                    $value = trim($value, ',');
                    $result = DB::table('setting_sys')->where('key', $key)->update(['value' => $value]);
                }
            }
        }
        $this->setCache();
        return intval($result);
    }

    //预警时间设置
    public function warnDaysLimit(Request $request) {
        $key = 'warn_days_limit';
        if($request->isMethod('POST')) {
            $post_data = $request->except(['_token']);
            $updata = [];
            $updata['value'] = serialize($post_data);
            $result = DB::table('setting_sys')->where('key', $key)->update($updata);
            $this->setCache();
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result >= 0 ? '1' : '0';
        }
        else {
            //查询信息
            $exist = isset(getCache('setting')[$key]);
            if(!$exist) {
                $insertdata = [];
                $insertdata['key'] = $key;
                $insertdata['remark'] = '预警时间设置';
                $insertdata['value'] = serialize(['days' => 30]);
                DB::table('setting_sys')->insert($insertdata);
                $this->setCache();
            }
            $data = unserialize(getCache('setting')[$key]);
            return view('admin.setting.warnDaysLimit', compact('data'));
        }
    }

    //设置
    public function settingSys($key) {
        if(request()->isMethod('POST')) {
            $post_data = request()->except(['_token', 'remark', 'method']);
            $value = json_decode(getCache('setting')[$key], true);
            $updata = [];
            if($key === 'letterFrom') {
                $updata['remark'] = '委托单规则来源';
                if(request()->input('method', '') === 'del') {
                    if((int)$value[$post_data['code']]['used'] === 0) {
                        unset($value[$post_data['code']]);
                    }
                }
                else {
                    if(isset($value[$post_data['code']])) {
                        return '数据已存在！';
                    }
                    $value[$post_data['code']] = $post_data;
                }
            }
            else {
                $value = $post_data;
            }
            $updata['value'] = json_encode($value);
            $result = DB::table('setting_sys')->where('key', $key)->update($updata);
            $this->setCache();
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result ? 1 : 0;
        }
        else {
            $exist = isset(getCache('setting')[$key]);
            if(!$exist) {
                $indata = [];
                $indata['key'] = $key;
                $indata['remark'] = request('remark', '');
                if(DB::table('setting_sys')->insert($indata)) {
                    $this->setCache();
                }
            }
            $data = json_decode(getCache('setting')[$key]);
            //查询信息
            return view('admin.setting.'.$key, compact('data'));
        }
    }

    //缓存
    public function setCache() {
        $seting = DB::table('setting_sys')->pluck('value', 'key');
        $seting['entrusted_company_default'] = isset($seting['entrusted_company_default']) ?: '';
        $seting['setting'] = DB::table('setting')->first();
        cache(['setting' => $seting], 999999);
        return $seting;
    }

    //数据库备份
    public function backUp() {
        try {
            $disk = Storage::disk('database');
        } catch(\Exception $exception) {
            return '未配置存储，请联系技术员！';
        }
        $dir = auth('admin')->user()->username;
        $disk->deleteDirectory($dir);
        $dbname = config('database.connections.mysql.database');
        $btObj = new BtApiController();
        //搜索获取数据库id
        $dbInfo = $btObj->searchDB($dbname);
        $dbData = data_get($dbInfo,'data',[]);
        if(count($dbData) == 0){
            return '数据中心查找失败！';
        }
        $id = 0;
        foreach($dbData as $item){
            if($item['name'] == $dbname){
                $id = $item['id'];
                break;
            }
        }
        //根据ID备份
        $back = $btObj->toBackUp($id);
        if(!$back){
            return '备份失败！';
        }
        if($back['status']) {
            //根据ID获取最近一次备份数据
            $backInfo = $btObj->getBackUp($id);
            $backData = $backInfo['data'];
            $crontabs = $btObj->getData([],'/crontab?action=GetCrontab');
            $backCount = 3;
            foreach ($crontabs as $key => $item) {
                if ($item['sType'] == 'database' && $item['status'] == 1) {
                    $backCount = $item['save'];
                    break;
                }
            }
            if(count($backData) > $backCount) {
                foreach($backData as $k => $item) {
                    if($k > 2) {
                        $btObj->delBackUp($item['id']);
                    }
                }
            }
        }
        return $back['msg'];
    }

    //还原数据库备份
    public function restoreBackUp() {
        $file = request()->file('restoreFile');
        $disk = Storage::disk('database');
        $dir = auth('admin')->user()->username;
        $disk->deleteDirectory($dir);
        $name = $file->getClientOriginalName();
        $path = $disk->putFileAs($dir, $file, $name);
        $toFileName = "/www/backup/database/{$name}";
        $from = $disk->getAdapter()->getPathPrefix().'/'.$path;
        $copy = copy($from, $toFileName);
        if($copy) {
            @unlink($from);
            $btObj = new BtApiController();
            //导入数据
            $dbname = config('database.connections.mysql.database');
            $p_data = [
                'file' => $toFileName,       // /www/backup/database/1.sql.gz
                'name' => $dbname,       //z_gqjjc03_vip
            ];
            $res = $btObj->getData($p_data, '/database?action=InputSql');
            //删除刚刚上传的文件
            $p_data = ['path' => $toFileName];
            $btObj->getData($p_data, '/files?action=DeleteFile');
            return $res['msg'];
        }
        return '操作失败！重新上传试试吧~';
    }
}
